package com.yidiandao.business.utils;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ScrollView;

/**
 * 监听键盘状态的Helper。
 * <p>
 * <p>
 * 可以通过{@link KeyboardStateHelper#setOnKeyboardStateChangeListener(OnKeyboardStateChangeListener)}
 * 来实时监听键盘的打开或关闭状态
 * <p>
 * 为避免出现内存泄露，请在对应的{@link AppCompatActivity#onDestroy()} 或者 {@link Fragment#onDestroy()}
 * 方法中调用 {@link KeyboardStateHelper#unregisterAllListeners()} 方法来解除监听
 * <p>
 * 注意:必须在`AndroidManifest`文件对应的`Activity`节点配置如下代码，以触发ScrollView的高度发生变化
 * <p>
 * android:windowSoftInputMode="adjustResize"
 * <p>
 * <p>
 * Created by ChenTao(chentao7v@gmail.com) on 2017/3/21 0021 17:17
 */
public class KeyboardStateHelper implements ViewTreeObserver.OnGlobalLayoutListener/*,
        View.OnFocusChangeListener */ {

    private ScrollView mScrollView;

    private OnKeyboardStateChangeListener mListener;

    private int initScrollViewHeight;

    private boolean savedInitScrollViewHeight = false;

    public KeyboardStateHelper(ScrollView scrollView) {
        mScrollView = scrollView;
        addGlobalLayoutListener();
    }

    private void addGlobalLayoutListener() {
        mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @Override
    public void onGlobalLayout() {
        if (!savedInitScrollViewHeight || initScrollViewHeight == 0) {
            initScrollViewHeight = mScrollView.getHeight();
            savedInitScrollViewHeight = true;
        }

        if (mScrollView.getHeight() < initScrollViewHeight) {
            // 键盘显示
            if (mListener != null) {
                mListener.onKeyboardStateChange(true);
            }
        } else {
            // 键盘隐藏
            if (mListener != null) {
                mScrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        mListener.onKeyboardStateChange(false);
                    }
                });
            }
        }
    }

    /**
     * 反注册监听
     */
    public void unregisterAllListeners() {
        mListener = null;
        mScrollView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }

    public void setOnKeyboardStateChangeListener(OnKeyboardStateChangeListener listener) {
        mListener = listener;
    }

    /**
     * 获得屏幕高度
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    public interface OnKeyboardStateChangeListener {

        void onKeyboardStateChange(boolean keyboardShow);
    }
}
